/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.abc.salesinventory.ui.newpackage;

import com.abc.salesinventory.model.newpackage.Customer;
import com.abc.salesinventory.model.newpackage.Product;
import com.abc.salesinventory.model.newpackage.Stock;
import com.abc.salesinventory.model.newpackage.Transaction;
import com.abc.salesinventory.model.newpackage.TransactionDetail;
import com.abc.salesinventory.service.newpackage.InventoryService;
import com.abc.salesinventory.service.newpackage.InventoryServiceImpl;
import com.abc.salesinventory.service.newpackage.MasterService;
import com.abc.salesinventory.service.newpackage.MasterServiceImpl;
import com.abc.salesinventory.service.sms.SMSMessageEngine;
import com.abc.salesinventory.util.DatePicker;
import com.abc.salesinventory.util.ReportViewer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Manuri
 */
public class Sales extends javax.swing.JInternalFrame {

    MasterService masterService = new MasterServiceImpl();
    InventoryService inventoryService = new InventoryServiceImpl();
    SMSMessageEngine engine = null;
    private JDesktopPane jDesktopPane = null;

    DefaultTableModel model = null;

    private void resetTable() {
        model = new DefaultTableModel();
        tableProductAmount.setModel(model);

        model.addColumn("Product Code");
        model.addColumn("Product Name");
        model.addColumn("Qty");
        model.addColumn("Discount");
        model.addColumn("Price");
        model.addColumn("Amount");
    }

    /**
     * Creates new form Sale
     */
    public Sales(SMSMessageEngine engine) {
        initComponents();
        this.engine = engine;
        resetTable();
        txtTransactionId.setText(UUID.randomUUID().toString());
        Set<Customer> customers = masterService.getAllCustomers();
        for (Customer customer : customers) {
            cmbCustomerName.addItem(customer);
        }
        List<Product> products = masterService.getAllProducts();
        for (Product product : products) {
            cmbProductName.addItem(product);
        }
        buttonGroup1.add(rbtnCash);
        buttonGroup1.add(rbtnCheque);
        
        currentDate();

    }
    
    public void currentDate(){
        Calendar cal = new GregorianCalendar();
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        ftxtDate.setText(year + "-" + (month+1)+"-"+day);
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        txtTransactionId = new javax.swing.JTextField();
        jLabel25 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel28 = new javax.swing.JLabel();
        cmbCustomerName = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        txtCustomerId = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel29 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtCategory = new javax.swing.JTextField();
        cmbProductName = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel30 = new javax.swing.JLabel();
        txtProductCode = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtUnitPrice = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        txtStockBalance = new javax.swing.JTextField();
        jLabel14 = new javax.swing.JLabel();
        jLabel31 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        btnAdd = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableProductAmount = new javax.swing.JTable();
        txtQty = new javax.swing.JTextField();
        txtDiscount = new javax.swing.JTextField();
        ftxtDate = new javax.swing.JTextField();
        btnViewStock = new javax.swing.JButton();
        rbtnCash = new javax.swing.JRadioButton();
        rbtnCheque = new javax.swing.JRadioButton();
        txtNetValue = new javax.swing.JTextField();
        btnNetValue = new javax.swing.JButton();
        jLabel35 = new javax.swing.JLabel();
        btnRemove = new javax.swing.JButton();
        btnAddTransaction = new javax.swing.JButton();
        btnCancelTransaction = new javax.swing.JButton();

        setClosable(true);
        setTitle("Sales");

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("Sales");

        jLabel22.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel22.setText("Transaction ID");

        jLabel25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel25.setForeground(new java.awt.Color(255, 0, 0));
        jLabel25.setText("*");

        jLabel24.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel24.setForeground(new java.awt.Color(255, 0, 0));
        jLabel24.setText("*");

        jLabel15.setFont(new java.awt.Font("Times New Roman", 1, 12)); // NOI18N
        jLabel15.setText("Date");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Customer Details");

        jLabel28.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel28.setForeground(new java.awt.Color(255, 0, 0));
        jLabel28.setText("*");

        cmbCustomerName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Select Customer Name--" }));
        cmbCustomerName.setToolTipText("");
        cmbCustomerName.setName(""); // NOI18N
        cmbCustomerName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbCustomerNameActionPerformed(evt);
            }
        });

        jLabel5.setText("Customer ID");

        txtCustomerId.setEditable(false);
        txtCustomerId.setFont(new java.awt.Font("Times New Roman", 0, 11)); // NOI18N
        txtCustomerId.setName(""); // NOI18N

        jLabel4.setText("Customer Name");

        jLabel29.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel29.setForeground(new java.awt.Color(255, 0, 0));
        jLabel29.setText("*");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Payment Method");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel7.setText("Item Details");

        txtCategory.setEditable(false);

        cmbProductName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Select Product--" }));
        cmbProductName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbProductNameActionPerformed(evt);
            }
        });

        jLabel10.setText("Category");

        jLabel9.setText("Product Code");

        jLabel30.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel30.setForeground(new java.awt.Color(255, 0, 0));
        jLabel30.setText("*");

        txtProductCode.setEditable(false);

        jLabel8.setText("Product Name");

        jLabel11.setText("Unit Price (Rs)");

        jLabel17.setText("Discount (%)");

        txtStockBalance.setEditable(false);

        jLabel14.setText("Stock Balance");

        jLabel31.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel31.setForeground(new java.awt.Color(255, 0, 0));
        jLabel31.setText("*");

        jLabel13.setText("Order Qty");

        btnAdd.setText("Add");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        tableProductAmount.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null},
                {null, null, null, null, null, null}
            },
            new String [] {
                "Product Code", "Product Name", "Qty", "Discount", "Price", "Amount"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableProductAmount);

        ftxtDate.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                ftxtDateMouseClicked(evt);
            }
        });

        btnViewStock.setText("View Stock Details");
        btnViewStock.setEnabled(false);
        btnViewStock.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnViewStockActionPerformed(evt);
            }
        });

        rbtnCash.setText("Cash");
        rbtnCash.setName(""); // NOI18N

        rbtnCheque.setText("Cheque");
        rbtnCheque.setName(""); // NOI18N

        txtNetValue.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        btnNetValue.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnNetValue.setText("Net Invoice Value");
        btnNetValue.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNetValueActionPerformed(evt);
            }
        });

        jLabel35.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel35.setForeground(new java.awt.Color(255, 0, 0));
        jLabel35.setText("*");

        btnRemove.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnRemove.setText("Remove Selected Item");
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });

        btnAddTransaction.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAddTransaction.setText("Save");
        btnAddTransaction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddTransactionActionPerformed(evt);
            }
        });

        btnCancelTransaction.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancelTransaction.setText("Cancel");
        btnCancelTransaction.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelTransactionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addComponent(jLabel22))
                            .addComponent(jLabel24))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtTransactionId, javax.swing.GroupLayout.PREFERRED_SIZE, 123, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(116, 116, 116)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(192, 192, 192)
                                .addComponent(jLabel25)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel15)
                                .addGap(18, 18, 18)
                                .addComponent(ftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(13, 13, 13)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(25, 25, 25)
                                .addComponent(jLabel28)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(cmbCustomerName, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(38, 38, 38)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txtCustomerId, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel7))))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(25, 25, 25)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel30)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtDiscount)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel11))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(cmbProductName, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel9)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(txtProductCode, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(txtUnitPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel31)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel13)
                            .addComponent(jLabel10)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel29)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(rbtnCash)
                                .addGap(18, 18, 18)
                                .addComponent(rbtnCheque))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addGap(193, 193, 193)
                                .addComponent(btnAdd)
                                .addGap(18, 18, 18)
                                .addComponent(btnClear)))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtCategory, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                    .addComponent(txtQty))
                .addGap(19, 19, 19)
                .addComponent(jLabel14)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtStockBalance, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(15, 15, 15))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnViewStock, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnRemove)
                        .addGap(87, 87, 87)
                        .addComponent(jLabel35)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnNetValue)
                        .addGap(18, 18, 18)
                        .addComponent(txtNetValue, javax.swing.GroupLayout.PREFERRED_SIZE, 133, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(btnAddTransaction)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelTransaction)
                        .addGap(93, 93, 93))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(15, 15, 15)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel22)
                    .addComponent(txtTransactionId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel24)
                    .addComponent(jLabel15)
                    .addComponent(jLabel25)
                    .addComponent(ftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cmbCustomerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)
                        .addComponent(txtCustomerId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(jLabel28)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(cmbProductName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel8)
                                        .addComponent(jLabel30))
                                    .addComponent(txtCategory, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(txtQty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel14)
                                    .addComponent(txtStockBalance, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel13)))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel11)
                                    .addComponent(txtDiscount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel17))
                                .addComponent(jLabel31)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel10)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(txtProductCode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jLabel9))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtUnitPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(btnViewStock)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnAdd)
                            .addComponent(btnClear))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(0, 23, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(jLabel29))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(rbtnCash)
                            .addComponent(rbtnCheque))))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNetValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnNetValue)
                    .addComponent(jLabel35)
                    .addComponent(btnRemove))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAddTransaction)
                    .addComponent(btnCancelTransaction))
                .addGap(27, 27, 27))
        );

        cmbCustomerName.getAccessibleContext().setAccessibleName("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cmbCustomerNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCustomerNameActionPerformed
        if (cmbCustomerName.getSelectedItem() != null && cmbCustomerName.getSelectedItem() instanceof Customer) {
            Customer customer = (Customer) cmbCustomerName.getSelectedItem();
            txtCustomerId.setText(customer.getId());
        } else {
            txtCustomerId.setText(null);
        }
    }//GEN-LAST:event_cmbCustomerNameActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        DefaultTableModel model = (DefaultTableModel) tableProductAmount.getModel();
        int selectedRow = tableProductAmount.getSelectedRow();
        if (selectedRow != -1) {
            model.removeRow(selectedRow);
        }
    }//GEN-LAST:event_btnRemoveActionPerformed
    
    private double getStockQty(String productCode) {
        List<Stock> stocks = inventoryService.getStockByProduct(productCode);
        double stockqty = 0.0d;
        if (stocks != null) {
            for (Stock stock : stocks) {
                stockqty = stockqty + stock.getQuantity();
            }
        }
        return stockqty;
    }
    private void cmbProductNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbProductNameActionPerformed
        if (cmbProductName.getSelectedIndex() != 0) {
            Product product = (Product) cmbProductName.getSelectedItem();
            txtProductCode.setText(product.getProductCode());
            txtCategory.setText(product.getCategory());

            txtStockBalance.setText("" + getStockQty(product.getProductCode()));
            btnViewStock.setEnabled(true);

        } else {
            txtProductCode.setText(null);
            txtCategory.setText(null);
            btnViewStock.setEnabled(false);
        }
    }//GEN-LAST:event_cmbProductNameActionPerformed
    private void Clear() {
        cmbProductName.setSelectedIndex(0);
        txtProductCode.setText(null);
        txtCategory.setText(null);
        txtUnitPrice.setText(null);
        txtStockBalance.setText(null);
        txtQty.setText(null);
        txtDiscount.setText(null);
    }

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        if (cmbProductName.getSelectedIndex() == 0 || txtUnitPrice.getText().trim().equals("") || txtQty.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(null, "One or more Required Fields are Empty !", "Add Sales Details", 2);
            return;
        } else {
            Double x = Double.parseDouble(txtQty.getText());
            Double y = Double.parseDouble(txtUnitPrice.getText());
            Double z = 0.0d;

            if (getStockQty(txtProductCode.getText()) < x) {
                JOptionPane.showMessageDialog(null, "Inventory does not have enough quantity to issue the requested quantity!", "Add Sales Details", 2);
                return;
            }

            Double discountAmount = 0.0d;
            if (txtDiscount.getText() != null && txtDiscount.getText() != "") {
                try {
                    z = Double.parseDouble(txtDiscount.getText());
                    discountAmount = (x * y) * z / 100;
                } catch (NumberFormatException e) {

                }
            }
            Double result = (x * y);

            Vector<Object> oneRow = new Vector<Object>();
            oneRow.add(txtProductCode.getText());
            oneRow.add(cmbProductName.getSelectedItem());
            oneRow.add(txtQty.getText());
            if (discountAmount > 0) {
                oneRow.add(txtDiscount.getText() + "%");
            } else {
                oneRow.add("0%");
            }
            oneRow.add(txtUnitPrice.getText());
            oneRow.add(result - discountAmount);

            model.addRow(oneRow);
            Clear();

        }
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnNetValueActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNetValueActionPerformed
        DefaultTableModel model = (DefaultTableModel) tableProductAmount.getModel();
        Vector dataModel = model.getDataVector();
        Iterator it = dataModel.iterator();
        double total = 0.0d;
        while (it.hasNext()) {
            Vector v = (Vector) it.next();
            total = total + (Double) v.get(5);
        }
        txtNetValue.setText("" + total);
    }//GEN-LAST:event_btnNetValueActionPerformed

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        Clear();
    }//GEN-LAST:event_btnClearActionPerformed

    private boolean validateSales() {
        boolean flag = true;
        if (txtTransactionId.getText() == null || txtTransactionId.getText().equals("")) {
            flag = false;
        }

        if (ftxtDate.getText() == null || ftxtDate.getText().equals("")) {
            flag = false;
        }

        if (txtCustomerId.getText() == null || txtCustomerId.getText().equals("")) {
            flag = false;
        }

        boolean radioFlag = false;
        if (rbtnCash.isSelected()) {
            radioFlag = true;
        } else if (rbtnCheque.isSelected()) {
            radioFlag = true;
        }

        if (!radioFlag) {
            flag = false;
        }

        DefaultTableModel model = (DefaultTableModel) tableProductAmount.getModel();
        Vector dataModel = model.getDataVector();

        if (dataModel == null || model.getRowCount() == 0) {
            flag = false;
        }

        if (flag == false) {
            JOptionPane.showMessageDialog(null, "One or more Required Fields are Empty !", "Purchase Details", 2);
        }

        return flag;
    }

    private void btnAddTransactionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddTransactionActionPerformed

        if (!validateSales()) {
            return;
        }

        Transaction transaction = new Transaction();

        Date txnDate = null;
        try {
            txnDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse(ftxtDate.getText());
        } catch (ParseException ex) {
            Logger.getLogger(Purchases.class.getName()).log(Level.SEVERE, null, ex);
        }
        transaction.setDate(txnDate);
        if (rbtnCash.isSelected()) {
            transaction.setPaymentMethod("CASH");
        } else if (rbtnCheque.isSelected()) {
            transaction.setPaymentMethod("CHEQUE");
        }

        Customer customer = ((Customer) cmbCustomerName.getSelectedItem());
        transaction.setCustomer(customer);

        transaction.setTransactionId(txtTransactionId.getText());
        transaction.setTransactionType("SALES");

        Set<TransactionDetail> transactionDetails = new HashSet<TransactionDetail>();

        DefaultTableModel model = (DefaultTableModel) tableProductAmount.getModel();
        Vector dataModel = model.getDataVector();
        Iterator it = dataModel.iterator();
        double total = 0.0d;
        int x = 0;
        while (it.hasNext()) {
            Vector v = (Vector) it.next();

            TransactionDetail detail = new TransactionDetail();

            String productCode = (String) v.get(0);
            Product product = masterService.getProduct(productCode);
            detail.setProduct(product);

            Double qty = Double.parseDouble((String) v.get(2));
            detail.setQuantity(qty);

            detail.setTransaction(transaction);
            detail.setTransactionDetailId(UUID.randomUUID().toString());

            Double uprice = Double.parseDouble((String) v.get(4));
            String discountStr = (String) v.get(3);
            Double discount = Double.parseDouble(discountStr.substring(0, discountStr.length() - 1));
            detail.setUnitPrice(uprice);
            detail.setDiscount(discount);

            total = total + (qty * uprice -(qty * uprice) * discount / 100);
//            Date expDate = null;
//            try {
//                expDate = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH).parse((String) v.get(2));
//            } catch (ParseException ex) {
//                Logger.getLogger(Purchases.class.getName()).log(Level.SEVERE, null, ex);
//            }
//            detail.setExpDate(expDate);
            transactionDetails.add(detail);

            if (getStockQty(productCode) < qty) {
                JOptionPane.showMessageDialog(null, "Inventory does not have enough quantity to issue the " + productCode + " quantity!", "Save Sales", 2);
                return;
            }

            double tempQty = qty;
            List<Stock> stocks = inventoryService.getStockByProduct(productCode);
            for (Stock stock : stocks) {
                if (tempQty > 0) {
                    if (tempQty >= stock.getQuantity()) {
                        masterService.removeStock(stock);
                    } else {
                        stock.setQuantity(stock.getQuantity() - tempQty);
                        masterService.saveOrUpdateStock(stock);
                    }
                    tempQty = tempQty - stock.getQuantity();
                } else {
                    break;
                }
            }

        }

        transaction.setTotal(total);

        transaction.setTransactionDetails(transactionDetails);
        inventoryService.saveTransaction(transaction);

        JOptionPane.showMessageDialog(null, "Sale successfully saved.", "Sales", 1);
        
        int reply = JOptionPane.showConfirmDialog(null, "Do you want to view Sales Invoice?", "Sales", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
            HashMap map = new HashMap();
            map.put("txnId", txtTransactionId.getText());
            getjDesktopPane().add(new ReportViewer("SalesInvoice.jrxml", map)).setVisible(true);
        }
        
        
        List list = inventoryService.getReorderStock();
        if (list != null) {
            getjDesktopPane().add(new AutomaticReorderPopup(engine)).setVisible(true);
        }

        ftxtDate.setText(null);
        cmbCustomerName.setSelectedIndex(0);
        rbtnCash.setSelected(false);
        rbtnCheque.setSelected(false);
        cmbProductName.setSelectedIndex(0);
        txtUnitPrice.setText(null);
        txtQty.setText(null);
        txtStockBalance.setText(null);
        txtDiscount.setText(null);
        currentDate();

        resetTable();

        txtNetValue.setText(null);
        txtTransactionId.setText(UUID.randomUUID().toString());
    }//GEN-LAST:event_btnAddTransactionActionPerformed

    private void ftxtDateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ftxtDateMouseClicked
        DatePicker datePicker = new DatePicker(jPanel1);
        ftxtDate.setText(datePicker.setPickedDate());
    }//GEN-LAST:event_ftxtDateMouseClicked

    private void btnCancelTransactionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelTransactionActionPerformed
        int reply = JOptionPane.showConfirmDialog(null, "This will cancel currentlt entered sales details. Do you want to continue?", "Warning", JOptionPane.YES_NO_OPTION);
        if (reply == JOptionPane.YES_OPTION) {
            dispose();
        }
    }//GEN-LAST:event_btnCancelTransactionActionPerformed

    private void btnViewStockActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnViewStockActionPerformed
        StockDetailsPopup popup = new StockDetailsPopup(null, true, txtProductCode.getText());
        popup.setVisible(true);
    }//GEN-LAST:event_btnViewStockActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Sales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Sales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Sales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Sales.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                SMSMessageEngine engine = new SMSMessageEngine();
                engine.init();
                new Sales(engine).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnAddTransaction;
    private javax.swing.JButton btnCancelTransaction;
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnNetValue;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnViewStock;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JComboBox cmbCustomerName;
    private javax.swing.JComboBox cmbProductName;
    private javax.swing.JTextField ftxtDate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel28;
    private javax.swing.JLabel jLabel29;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel30;
    private javax.swing.JLabel jLabel31;
    private javax.swing.JLabel jLabel35;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbtnCash;
    private javax.swing.JRadioButton rbtnCheque;
    private javax.swing.JTable tableProductAmount;
    private javax.swing.JTextField txtCategory;
    private javax.swing.JTextField txtCustomerId;
    private javax.swing.JTextField txtDiscount;
    private javax.swing.JTextField txtNetValue;
    private javax.swing.JTextField txtProductCode;
    private javax.swing.JTextField txtQty;
    private javax.swing.JTextField txtStockBalance;
    private javax.swing.JTextField txtTransactionId;
    private javax.swing.JTextField txtUnitPrice;
    // End of variables declaration//GEN-END:variables

    public JDesktopPane getjDesktopPane() {
        return jDesktopPane;
    }

    public void setjDesktopPane(JDesktopPane jDesktopPane) {
        this.jDesktopPane = jDesktopPane;
    }
}
